{% extends "后台管理/template.html" %}

{% block title %}
分类管理
{% endblock %}

{% block css %}
<style>
    .category-tabs {
        display: flex;
        gap: 12px;
        margin-bottom: 24px;
        overflow-x: auto;
        padding-bottom: 8px;
    }

    .category-tab {
        padding: 8px 20px;
        border-radius: 20px;
        background: #f5f5f5;
        color: #666;
        cursor: pointer;
        transition: all 0.3s ease;
        white-space: nowrap;
        display: flex;
        align-items: center;
        gap: 8px;
        border: 1px solid transparent;
    }

    .category-tab:hover {
        background: #eef2ff;
        color: #696cff;
    }

    .category-tab.active {
        background: #696cff;
        color: #fff;
    }

    .category-tab .count {
        background: rgba(255,255,255,0.2);
        padding: 2px 8px;
        border-radius: 10px;
        font-size: 12px;
    }

    .category-tab:not(.active) .count {
        background: #e0e0e0;
    }

    .post-grid {
        column-count: 1;
        column-gap: 20px;
        padding: 10px;
        max-width: 1400px;
        margin: 0 auto;
    }

    @media (min-width: 768px) {
        .post-grid {
            column-count: 2;
        }
    }

    @media (min-width: 992px) {
        .post-grid {
            column-count: 3;
        }
    }

    @media (min-width: 1200px) {
        .post-grid {
            column-count: 4;
        }
    }

    .post-card {
        break-inside: avoid;
        margin-bottom: 20px;
        background: #fff;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 2px 12px rgba(0,0,0,0.08);
        border: 1px solid #ebeef5;
        transition: all 0.3s ease;
    }

    .post-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0,0,0,0.12);
    }

    .post-cover-wrapper {
        position: relative;
        width: 100%;
        overflow: hidden;
    }

    .post-cover {
        width: 100%;
        height: auto;
        display: block;
        object-fit: cover;
    }

    .post-content-wrapper {
        padding: 16px;
    }

    .post-header {
        margin-bottom: 12px;
    }

    .post-title {
        font-size: 16px;
        font-weight: 600;
        color: #2c2c2c;
        margin: 0;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        line-height: 1.4;
    }

    .post-content {
        color: #666;
        font-size: 14px;
        margin-bottom: 12px;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
        line-height: 1.5;
        flex: 1;
    }

    .post-footer {
        margin-top: auto;
        padding-top: 12px;
        border-top: 1px solid #f0f0f0;
    }

    .post-meta {
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: #999;
        font-size: 13px;
    }

    .post-author {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .author-avatar {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        object-fit: cover;
    }

    .post-stats {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .post-stat {
        display: flex;
        align-items: center;
        gap: 4px;
    }

    .pinned-badge {
        position: absolute;
        top: 12px;
        right: 12px;
        background: rgba(0, 0, 0, 0.5);
        color: #fff;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        display: inline-flex;
        align-items: center;
        gap: 4px;
        backdrop-filter: blur(4px);
        z-index: 1;
    }

    .empty-tip {
        text-align: center;
        padding: 40px 0;
        color: #999;
    }

    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255,255,255,0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }

    .category-panel {
        position: fixed;
        top: 0;
        right: -300px;
        width: 300px;
        height: 100%;
        background: #fff;
        box-shadow: -2px 0 12px rgba(0,0,0,0.1);
        transition: right 0.3s ease;
        z-index: 1000;
        overflow-y: auto;
        padding: 20px;
    }

    .category-panel.open {
        right: 0;
    }

    .category-panel-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .category-panel-header h5 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
    }

    .category-panel-close {
        cursor: pointer;
        font-size: 20px;
        color: #999;
    }

    .category-panel-close:hover {
        color: #333;
    }

    .category-panel-list {
        list-style: none;
        padding: 0;
        margin: 0;
    }

    .category-panel-item {
        padding: 10px 0;
        border-bottom: 1px solid #f0f0f0;
        cursor: pointer;
        transition: background 0.3s ease;
    }

    .category-panel-item:hover {
        background: #f9f9f9;
    }

    .category-panel-item.active {
        background: #eef2ff;
        color: #696cff;
    }

    .category-panel-toggle {
        position: fixed;
        top: 50%;
        right: 0;
        transform: translateY(-50%);
        width: 40px;
        height: 40px;
        background: #696cff;
        color: #fff;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        transition: background 0.3s ease;
        z-index: 1001;
    }

    .category-panel-toggle:hover {
        background: #5f62e6;
    }

    .category-panel.open + .category-panel-toggle {
        right: 300px; /* 确保面板打开时图标不被遮挡 */
    }

    .post-detail-panel {
        position: fixed;
        top: 0;
        right: -400px;
        width: 400px;
        height: 100%;
        background: #fff;
        box-shadow: -2px 0 12px rgba(0,0,0,0.1);
        transition: right 0.3s ease;
        z-index: 1000;
        overflow-y: auto;
        padding: 20px;
    }

    .post-detail-panel.open {
        right: 0;
    }

    .post-detail-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .post-detail-header h5 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
    }

    .post-detail-close {
        cursor: pointer;
        font-size: 20px;
        color: #999;
    }

    .post-detail-close:hover {
        color: #333;
    }

    .post-detail-content {
        color: #666;
        font-size: 14px;
        line-height: 1.6;
    }

    .user-id-input {
        margin-bottom: 20px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 添加分类按钮 -->
    <div class="mb-4 d-flex align-items-center justify-content-between">
        <button class="btn btn-primary" onclick="showAddCategoryModal()">
            <i class='bx bx-plus me-1'></i>添加分类
        </button>
        <input type="text" id="userIdInput" class="form-control w-auto ms-3" placeholder="请输入用户ID..." oninput="storeUserId(this.value)" style="max-width: 200px;">
    </div>

    <!-- 分类切换栏 -->
    <div class="category-tabs" id="categoryTabs">
        <!-- 分类标签将通过JS动态插入 -->
    </div>

    <!-- 帖子列表 -->
    <div id="postList">
        <!-- 帖子列表将通过JS动态插入 -->
    </div>

    <!-- 分页器 -->
    <nav class="d-flex justify-content-center mt-4" id="pagination" style="display: none;">
        <ul class="pagination">
            <!-- 分页按钮将通过JS动态插入 -->
        </ul>
    </nav>

    <!-- 加载中遮罩 -->
    <div class="loading-overlay" id="loadingOverlay" style="display: none;">
        <div class="spinner-border text-primary" role="status">
            <span class="sr-only">加载中...</span>
        </div>
    </div>

    <!-- 添加分类模态框 -->
    <div class="modal fade" id="categoryModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加分类</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="categoryForm">
                        <div class="mb-3">
                            <label class="form-label">分类名称</label>
                            <input type="text" class="form-control" id="categoryName" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitCategory()">
                        <i class='bx bx-save me-1'></i>保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="category-panel" id="categoryPanel">
        <div class="category-panel-header">
            <h5>分类列表</h5>
            <span class="category-panel-close" onclick="toggleCategoryPanel()">&times;</span>
        </div>
        <ul class="category-panel-list" id="categoryPanelList">
            <!-- 分类列表将通过JS动态插入 -->
        </ul>
    </div>

    <div class="category-panel-toggle" onclick="toggleCategoryPanel()">
        <i class='bx bx-menu'></i>
    </div>

    <div class="post-detail-panel" id="postDetailPanel">
        <div class="post-detail-header">
            <h5>帖子详情</h5>
            <span class="post-detail-close" onclick="togglePostDetailPanel()">&times;</span>
        </div>
        <div class="post-detail-content" id="postDetailContent">
            <!-- 帖子内容将通过JS动态插入 -->
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
let categoryModal = null;
let currentCategoryId = null;
let currentPage = 1;
const pageSize = 10;

// 分页相关变量
let categoryPage = 1;
const categoryPageSize = 50; // 每页显示50个分类

let userId = null; // 用户ID变量

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    categoryModal = new bootstrap.Modal(document.getElementById('categoryModal'));
    getCategoryList();
});

// 获取分类列表
async function getCategoryList() {
    try {
        showLoading();
        const response = await fetch(`/api/post/get_category/?page=${categoryPage}&page_size=${categoryPageSize}`);
        const data = await response.json();
        
        if(data.code === 200) {
            renderCategoryTabs(data.data);
            renderCategoryPanel(data.data);
            if(data.data.length > 0 && categoryPage === 1) {
                switchCategory(data.data[0].id);
            }
        } else {
            throw new Error(data.message);
        }
    } catch(error) {
        console.error('获取分类列表失败:', error);
        showToast('获取分类列表失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 渲染分类标签
function renderCategoryTabs(categories) {
    const container = document.getElementById('categoryTabs');
    
    if(!categories || categories.length === 0) {
        container.innerHTML = '<div class="empty-tip">暂无分类</div>';
        return;
    }
    
    container.innerHTML = categories.map(category => `
        <div class="category-tab ${category.id === currentCategoryId ? 'active' : ''}" 
             onclick="switchCategory(${category.id})">
            <span>${category.name}</span>
            <span class="count" id="count-${category.id}">0</span>
        </div>
    `).join('');
}

// 切换分类
async function switchCategory(categoryId) {
    currentCategoryId = categoryId;
    currentPage = 1;
    
    // 更新标签样式
    document.querySelectorAll('.category-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    document.querySelector(`.category-tab[onclick="switchCategory(${categoryId})"]`)?.classList.add('active');
    
    // 获取该分类的帖子
    await getCategoryPosts();
}

// 获取分类帖子
async function getCategoryPosts() {
    if(!currentCategoryId) return;
    
    try {
        showLoading();
        const response = await fetch(`/api/post/get_category_post/?category_id=${currentCategoryId}&page=${currentPage}&page_size=${pageSize}`);
        const data = await response.json();
        
        if(data.code === 200) {
            renderPostList(data.data);
            // 更新帖子数量
            const countElement = document.getElementById(`count-${currentCategoryId}`);
            if(countElement) {
                countElement.textContent = data.data.length;
            }
        } else {
            throw new Error(data.message);
        }
    } catch(error) {
        console.error('获取帖子列表失败:', error);
        showToast('获取帖子列表失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 渲染帖子列表
function renderPostList(posts) {
    const container = document.getElementById('postList');
    
    if(!posts || posts.length === 0) {
        container.innerHTML = `
            <div class="empty-tip">
                <i class='bx bx-info-circle fs-3 mb-2'></i>
                <p>该分类下暂无帖子</p>
            </div>
        `;
        return;
    }
    
    container.innerHTML = `
        <div class="post-grid">
            ${posts.map(post => {
                const handleImageLoad = `
                    onload="this.style.opacity='1'"
                    onerror="this.parentElement.style.display='none'"
                    style="opacity: 0; transition: opacity 0.3s ease;"
                `;
                
                return `
                    <div class="post-card" onclick="getPostDetail(${post.id})">
                        ${post.cover ? `
                            <div class="post-cover-wrapper">
                                ${post.is_pinned ? `
                                    <span class="pinned-badge">
                                        <i class='bx bx-pin'></i>置顶
                                    </span>
                                ` : ''}
                                <img src="${post.cover}" 
                                     class="post-cover" 
                                     alt="封面图" 
                                     loading="lazy"
                                     ${handleImageLoad}>
                            </div>
                        ` : ''}
                        <div class="post-content-wrapper">
                            <div class="post-header">
                                <h3 class="post-title">${post.title}</h3>
                            </div>
                            
                            <div class="post-content">
                                ${post.content}
                            </div>
                            
                            <div class="post-footer">
                                <div class="post-meta">
                                    <div class="post-author">
                                        <img src="${post.user.avatar}" 
                                             class="author-avatar" 
                                             alt="头像" 
                                             loading="lazy"
                                             onerror="this.src='/static/images/default-avatar.jpg'">
                                        <span>${post.user.username}</span>
                                    </div>
                                    <div class="post-stats">
                                        <span class="post-stat">
                                            <i class='bx bx-heart'></i>
                                            <span>${post.likes}</span>
                                        </span>
                                        <span class="post-stat">
                                            <i class='bx bx-time'></i>
                                            <span>${formatDateTime(post.create_time)}</span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            }).join('')}
        </div>
    `;

    // 监听所有图片加载完成
    const images = container.getElementsByTagName('img');
    Array.from(images).forEach(img => {
        if (img.complete) {
            img.style.opacity = '1';
        }
    });
}

// 格式化日期时间
function formatDateTime(dateStr) {
    const date = new Date(dateStr.replace(/-/g, '/'));
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 显示加载中
function showLoading() {
    document.getElementById('loadingOverlay').style.display = 'flex';
}

// 隐藏加载中
function hideLoading() {
    document.getElementById('loadingOverlay').style.display = 'none';
}

// 显示添加分类模态框
function showAddCategoryModal() {
    document.getElementById('categoryForm').reset();
    categoryModal.show();
}

// 提交分类表单
async function submitCategory() {
    const form = document.getElementById('categoryForm');
    const name = document.getElementById('categoryName').value.trim();
    
    if(!name) {
        showToast('请输入分类名称', 'error');
        return;
    }
    
    try {
        showLoading();
        
        // 添加分类
        const response = await fetch('/api/post/create_category/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `name=${encodeURIComponent(name)}`
        });
        
        const data = await response.json();
        if(data.code === 200) {
            showToast('添加成功', 'success');
            getCategoryList(); // 刷新列表
        } else {
            throw new Error(data.message);
        }
        
        categoryModal.hide();
    } catch(error) {
        console.error('操作失败:', error);
        showToast('操作失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 搜索分类
function searchCategory(keyword) {
    const tabs = document.querySelectorAll('.category-tab');
    tabs.forEach(tab => {
        const name = tab.querySelector('span').textContent.toLowerCase();
        if(name.includes(keyword.toLowerCase())) {
            tab.style.display = 'flex';
        } else {
            tab.style.display = 'none';
        }
    });
}

// 添加搜索框
const searchInput = document.createElement('input');
searchInput.type = 'text';
searchInput.placeholder = '搜索分类...';
searchInput.className = 'form-control mb-3';
searchInput.addEventListener('input', (e) => searchCategory(e.target.value));
document.querySelector('.category-tabs').insertAdjacentElement('beforebegin', searchInput);

// 切换分类面板
function toggleCategoryPanel() {
    const panel = document.getElementById('categoryPanel');
    panel.classList.toggle('open');
}

// 渲染分类面板列表
function renderCategoryPanel(categories) {
    const panelList = document.getElementById('categoryPanelList');
    
    if(!categories || categories.length === 0) {
        panelList.innerHTML = '<li class="text-center text-muted">暂无分类</li>';
        return;
    }
    
    panelList.innerHTML = categories.map(category => `
        <li class="category-panel-item ${category.id === currentCategoryId ? 'active' : ''}" 
            onclick="switchCategory(${category.id})">
            ${category.name}
        </li>
    `).join('');
}

// 切换帖子详情面板
function togglePostDetailPanel() {
    const panel = document.getElementById('postDetailPanel');
    panel.classList.toggle('open');
}

// 存储用户ID
function storeUserId(value) {
    userId = value.trim();
}

// 获取帖子详情
async function getPostDetail(postId) {
    if (!userId) {
        showToast('请输入用户ID', 'error');
        return;
    }
    try {
        showLoading();
        const response = await fetch(`/api/post/get_post_detail/?user_id=${userId}&post_id=${postId}`);
        const data = await response.json();
        
        if (data.code === 200) {
            renderPostDetail(data.data);
            togglePostDetailPanel();
            await getPostMedia(postId); // 获取媒体资源
        } else {
            throw new Error(data.message);
        }
    } catch (error) {
        console.error('获取帖子详情失败:', error);
        showToast('获取帖子详情失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 获取帖子媒体资源
async function getPostMedia(postId) {
    try {
        const response = await fetch(`/api/post/get_post_media/?post_id=${postId}`);
        const data = await response.json();
        
        if (data.code === 200) {
            renderPostMedia(data.data);
        } else {
            throw new Error(data.message);
        }
    } catch (error) {
        console.error('获取媒体资源失败:', error);
        showToast('获取媒体资源失败: ' + error.message, 'error');
    }
}

// 渲染帖子媒体资源
function renderPostMedia(mediaList) {
    const content = document.getElementById('postDetailContent');
    const mediaContainer = document.createElement('div');
    mediaContainer.className = 'media-container';
    
    if (!mediaList || mediaList.length === 0) {
        mediaContainer.innerHTML = '<p class="text-muted">暂无媒体资源</p>';
    } else {
        const images = mediaList.filter(media => media.media_type === '图片');
        const videos = mediaList.filter(media => media.media_type === '视频');
        
        if (images.length > 0) {
            const carouselId = 'carouselExampleControls';
            const carousel = document.createElement('div');
            carousel.className = 'carousel slide';
            carousel.id = carouselId;
            carousel.setAttribute('data-bs-ride', 'carousel');
            carousel.innerHTML = `
                <div class="carousel-inner">
                    ${images.map((img, index) => `
                        <div class="carousel-item ${index === 0 ? 'active' : ''}">
                            <a href="${img.media_url}" data-lightbox="post-images">
                                <img src="${img.media_url}" class="d-block w-100" alt="图片">
                            </a>
                        </div>
                    `).join('')}
                </div>
                <button class="carousel-control-prev" type="button" data-bs-target="#${carouselId}" data-bs-slide="prev">
                    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                    <span class="visually-hidden">Previous</span>
                </button>
                <button class="carousel-control-next" type="button" data-bs-target="#${carouselId}" data-bs-slide="next">
                    <span class="carousel-control-next-icon" aria-hidden="true"></span>
                    <span class="visually-hidden">Next</span>
                </button>
            `;
            mediaContainer.appendChild(carousel);
        }
        
        videos.forEach(video => {
            const videoElement = document.createElement('video');
            videoElement.controls = true;
            videoElement.src = video.media_url;
            videoElement.className = 'w-100 mb-3';
            mediaContainer.appendChild(videoElement);
        });
    }
    
    content.appendChild(mediaContainer);
}

// 渲染帖子详情
function renderPostDetail(post) {
    const content = document.getElementById('postDetailContent');
    content.innerHTML = `
        <h3>${post.title}</h3>
        <p>${post.content}</p>
        <div class="post-meta">
            <span>作者: ${post.user.username}</span>
            <span>发布时间: ${formatDateTime(post.create_time)}</span>
        </div>
    `;
}

// 页面卸载时清空用户ID
window.addEventListener('beforeunload', () => {
    userId = null;
});

// 在页面加载时引入 lightbox 库
const lightboxLink = document.createElement('link');
lightboxLink.rel = 'stylesheet';
lightboxLink.href = 'https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.min.css';
document.head.appendChild(lightboxLink);

const lightboxScript = document.createElement('script');
lightboxScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/js/lightbox.min.js';
document.body.appendChild(lightboxScript);
</script>
{% endblock %}

{% block nav_left %}
{% endblock %}

{% block NavBar %}
{% include '后台管理/components/左侧导航栏.html' %}
{% endblock %}

{% block footer %}
{% include '后台管理/components/Footer.html' %}
{% endblock %}